package com.kzw.config;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * 解决跨域访问的过滤器
 * */
@WebFilter(filterName = "myFilter",urlPatterns = "/*")
public class CorsFilter implements Filter {
	
	// 允许缓存的文件
	private static final String[] caches = {"js", "css", "woff", "jpg", "png", "gif", "jpeg", "ico"};
 
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse) res;
		
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		response.setHeader("Access-Control-Max-Age", "3600");
		response.setHeader("Access-Control-Allow-Headers", "Authentication,Origin, X-Requested-With, Content-Type, Accept");
		response.setHeader("Access-Control-Expose-Headers", "Authorization");
		
		// 只缓存静态文件
		String suffix = FilenameUtils.getExtension(request.getRequestURI());
		if(StringUtils.containsAny(suffix, caches)) {
			response.setHeader("Cache-Control", "max-age=3600000");
		}
		
		chain.doFilter(req, res);
	}
	
	public void init(FilterConfig filterConfig) {}
	public void destroy() {}
}
